class QuestionsController < ApplicationController
  before_filter :login_required
  before_filter :question_pool_required

  def index
    question_pool = session[:current_question_pool]
    @question_pool_name = question_pool.name
    @questions = Question.find :all
    @questions = @questions.select {|question| question.categories.include?(question_pool)}
  end
  
  def show
    @question = Question.find params[:id]
    @minutes  = @question.max_time / 60
    @seconds  = @question.max_time % 60
    @question_categories = @question.categories - [ session[:current_question_pool] ]
  end
  
  def new
    @question = Question.new
    4.times { @question.answers.build }
    @question_types = ["Selection", "Multi-selection", "Textual"]
    @root_categories = session[:current_question_pool].children
  end
  
  def create
    params[:question][:max_time] = params[:question][:minutes].to_i.minutes + params[:question][:seconds].to_i
    params[:question].delete(:minutes); params[:question].delete(:seconds)

    @question = Question.new params[:question]
    @question.difficulty = 0.5
    @question.creator_id = current_user
    initial_categories = @question.categories
    initial_categories.each do |cat| @question.categories |= cat.ancestors end
    @question.categories |= [ session[:current_question_pool] ] # in case no categories have been selected
    if @question.save
      flash[:notice] = 'Question successfully added'
      redirect_to questions_path
    else
      render :action => 'new'
    end
  end
  
  def edit
    @question = Question.find params[:id]
    @minutes = @question.max_time / 60
    @seconds = @question.max_time % 60
    @question_types = ["Selection", "Multi-selection", "Textual"]
    @root_categories = session[:current_question_pool].children  
  end

  def update
    params[:question][:existing_answer_attributes] ||= {}
    params[:question][:category_ids] ||= []
    
    params[:question][:max_time] = params[:question][:minutes].to_i.minutes + params[:question][:seconds].to_i
    params[:question].delete(:minutes); params[:question].delete(:seconds)
    
    @question = Question.find params[:id]
    if @question.update_attributes(params[:question])
      ## TBD: It'd better before udpate
      initial_categories = @question.categories
      initial_categories.each do |cat| @question.categories |= cat.ancestors end
      @question.categories |= [ session[:current_question_pool] ] # in case no categories have been selected
      flash[:notice] = 'Question was successfully updated'
      redirect_to :action => 'show', :id => @question
    else
      render :action => 'edit'
    end
  end
  
  def destroy
    @question = Question.find params[:id]
    @question.destroy
    redirect_to questions_path
  end
end
